@using System.Diagnostics.CodeAnalysis
@using nERP.ViewModel.HomeVMs
@inherits BasePage

<div class="row g-3">
    <div class="col-12">
        <div class="d-flex align-items-center">
            <div class="flex-fill text-dark fw-bold me-3">仪表板</div>
            <DateTimePicker Value="DateTimePickerValue" OnValueChanged="OnDateTimePickerValueChanged" />
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <Card IsShadow="true">
            <BodyTemplate>
                <div class="row align-items-center no-gutters">
                    <div class="col me-2">
                        <div class=" text-primary fw-bold mb-1"><span>销售总额</span></div>
                        <div class="text-dark fw-bold h5">
                            <CountUp Value="@Model.SoAmount"></CountUp>
                        </div>
                        <div class=" text-info fw-bold mb-1"><span>已签发销售总额</span></div>
                        <div class="row g-0 align-items-center">
                            <div class="col-auto">
                                <div class="text-dark fw-bold h5 me-3 mb-0">
                                    <CountUp Value="@Model.SoAmounted"></CountUp>
                                </div>
                            </div>
                            <div class="col"><div class="db-progress"><BootstrapBlazor.Components.Progress Value="@Model.SoScale" IsShowValue="true" Round="1"></BootstrapBlazor.Components.Progress></div></div>
                        </div>
                    </div>
                    <div class="col-auto"><i class="fa-regular fa-calendar-check fa-2x"></i></div>
                </div>
            </BodyTemplate>
        </Card>
    </div>
    <div class="col-md-6 col-xl-3">
        <Card IsShadow="true">
            <BodyTemplate>
                <div class="row align-items-center no-gutters">
                    <div class="col me-2">
                        <div class=" text-primary fw-bold mb-1"><span>采购总额</span></div>
                        <div class="text-dark fw-bold h5">
                            <CountUp Value="@Model.PoAmount"></CountUp>
                        </div>
                        <div class=" text-info fw-bold mb-1"><span>已签发采购总额</span></div>
                        <div class="row g-0 align-items-center">
                            <div class="col-auto">
                                <div class="text-dark fw-bold h5 me-3 mb-0">
                                    <CountUp Value="@Model.PoAmounted"></CountUp>
                                </div>
                            </div>
                            <div class="col"><div class="db-progress"><BootstrapBlazor.Components.Progress Value="@Model.PoScale" IsShowValue="true" Round="1"></BootstrapBlazor.Components.Progress></div></div>
                        </div>
                    </div>
                    <div class="col-auto"><i class="fa-regular fa-calendar-check fa-2x"></i></div>
                </div>
            </BodyTemplate>
        </Card>
    </div>
    <div class="col-md-6 col-xl-3">
        <Card IsShadow="true">
            <BodyTemplate>
                <div class="row align-items-center no-gutters">
                    <div class="col me-2">
                        <div class=" text-primary fw-bold mb-1"><span>收款总额</span></div>
                        <div class="text-dark fw-bold h5">
                            <CountUp Value="@Model.ReceivableAmount"></CountUp>
                        </div>
                        <div class=" text-info fw-bold mb-1"><span>已签发收款总额</span></div>
                        <div class="row g-0 align-items-center">
                            <div class="col-auto">
                                <div class="text-dark fw-bold h5 me-3 mb-0">
                                    <CountUp Value="@Model.ReceivableAmounted"></CountUp>
                                </div>
                            </div>
                            <div class="col"><div class="db-progress"><BootstrapBlazor.Components.Progress Value="@Model.ReceivableScale" IsShowValue="true" Round="1"></BootstrapBlazor.Components.Progress></div></div>
                        </div>
                    </div>
                    <div class="col-auto"><i class="fa-regular fa-calendar-check fa-2x"></i></div>
                </div>
            </BodyTemplate>
        </Card>
    </div>
    <div class="col-md-6 col-xl-3">
        <Card IsShadow="true">
            <BodyTemplate>
                <div class="row align-items-center no-gutters">
                    <div class="col me-2">
                        <div class=" text-primary fw-bold mb-1"><span>付款总额</span></div>
                        <div class="text-dark fw-bold h5">
                            <CountUp Value="@Model.PayAmount"></CountUp>
                        </div>
                        <div class=" text-info fw-bold mb-1"><span>已签发付款总额</span></div>
                        <div class="row g-0 align-items-center">
                            <div class="col-auto">
                                <div class="text-dark fw-bold h5 me-3 mb-0">
                                    <CountUp Value="@Model.PayAmounted"></CountUp>
                                </div>
                            </div>
                            <div class="col"><div class="db-progress"><BootstrapBlazor.Components.Progress Value="@Model.PayScale" IsShowValue="true" Round="1"></BootstrapBlazor.Components.Progress></div></div>
                        </div>
                    </div>
                    <div class="col-auto"><i class="fa-regular fa-calendar-check fa-2x"></i></div>
                </div>
            </BodyTemplate>
        </Card>
    </div>
    <div class="col-md-6">
        <Card IsShadow="true" HeaderText="账户现金">
            <BodyTemplate>
                <div class="chart-area">
                    <Chart @ref="BarChart" Height="320px" Width="auto" style="display: block; width: auto; height: 320px;"
                           ChartType="ChartType.Bar" OnInitAsync="OnInitBarChartAsync"></Chart>
                </div>
            </BodyTemplate>
        </Card>
    </div>
    <div class="col-md-6">
        <Card IsShadow="true" HeaderText="库龄">
            <BodyTemplate>
                <div class="chart-area">
                    <Chart @ref="PieChart" Height="320px" Width="auto" style="display: block; width: 332px; height: 320px;"
                           ChartType="ChartType.Doughnut" OnInitAsync="@OnInitPieChartAsync"></Chart>
                </div>
            </BodyTemplate>
        </Card>
    </div>
    <div class="col-md-6">
        <Card IsShadow="true" HeaderText="入库 Top 10">
            <BodyTemplate>
                <Scroll Height="250px" style="overflow:scroll;">
                    <div style="margin-right:10px;">
                        @{
                            if (buyTop != null)
                            {
                                foreach (var item in buyTop)
                                {
                                    <h4 class="small fw-bold">
                                        @item.BuyCode<span class="float-end">
                                            @(
                                            GetD(item.TotalPrice1)
                                                )%
                                        </span>
                                    </h4>
                                    <BootstrapBlazor.Components.Progress Value="@GetD(item.TotalPrice1)" IsAnimated="true" Color="@GetColor(GetD(item.TotalPrice1))" IsShowValue="true" Round="1" />
                                }
                            }
                            else
                            {
                                <BootstrapBlazor.Components.Progress Value="0" IsAnimated="true" Color="@GetColor(0)" IsShowValue="true" Round="1" />
                            }
                        }
                    </div>
                </Scroll>
            </BodyTemplate>
        </Card>
    </div>
    <div class="col-md-6">
        <Card IsShadow="true" HeaderText="出库 Top 10">
            <BodyTemplate>
                <Scroll Height="250px" style="overflow:scroll;">
                    <div style="margin-right:10px;">
                        @{
                            if (saleTop != null)
                            {
                                foreach (var item in saleTop)
                                {
                                    <h4 class="small fw-bold">
                                        @item.SaleCode<span class="float-end">
                                            @(
                                            GetD(item.TotalPrice1)
                                                )%
                                        </span>
                                    </h4>
                                    <BootstrapBlazor.Components.Progress Value="@GetD(item.TotalPrice1)" IsAnimated="true" Color="@GetColor(GetD(item.TotalPrice1))" IsShowValue="true" Round="1" />
                                }
                            }
                            else
                            {
                                <BootstrapBlazor.Components.Progress Value="0" IsAnimated="true" Color="@GetColor(0)" IsShowValue="true" Round="1" />
                            }
                        }
                    </div>
                </Scroll>
            </BodyTemplate>
        </Card>
    </div>
</div>
@code {

    [Parameter]
    public Index.githubpoco model { get; set; } = new Index.githubpoco();

    [NotNull]
    private Chart? BarChart { get; set; }

    [NotNull]
    private Chart? PieChart { get; set; }
    private DateTime DateTimePickerValue { get; set; } = DateTime.Today;

    [NotNull]
    private DashboardData? Data { get; set; }

    private nERP.Model.Rpt.Dashboard Model { get; set; } = new Model.Rpt.Dashboard();
    private List<nERP.Model.Wms.BuyInWarehouseDetail> buyPie { get; set; } = new List<Model.Wms.BuyInWarehouseDetail>();
    private List<nERP.Model.Po.Buy> buyTop { get; set; } = new List<Model.Po.Buy>();
    private List<nERP.Model.So.Sale> saleTop { get; set; } = new List<Model.So.Sale>();
    /// <summary>
    /// <inheritdoc/>
    /// </summary>
    /// <returns></returns>
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        Data = await GetDashboardDataAsync();

        await ResetData();

    }
    private async Task ResetData()
    {
        var rv = await WtmBlazor.Api.CallAPI<nERP.Model.Rpt.Dashboard>($"/api/Rpt/Dashboard/GetDashboard");
        Model = rv.Data;
        if (Model != null)
        {
            var po = Model.PoAmount == 0 ? 0 : Math.Round((double)Model.PoAmounted / (double)Model.PoAmount * 100, 1);
            Model.PoScale = po is double.NaN ? 0 : po;
            var so = Model.SoAmount == 0 ? 0 : Math.Round((double)Model.SoAmounted / (double)Model.SoAmount * 100, 1);
            Model.SoScale = so is double.NaN ? 0 : so;
            var receivable = Model.ReceivableAmount == 0 ? 0 : Math.Round((double)Model.ReceivableAmounted / (double)Model.ReceivableAmount * 100, 1);
            Model.ReceivableScale = receivable is double.NaN ? 0 : receivable;
            var pay = Model.PayAmount == 0 ? 0 : Math.Round((double)Model.PayAmounted / (double)Model.PayAmount * 100, 1);
            Model.PayScale = pay is double.NaN ? 0 : pay;
        }
        else
        {
            Model = new Model.Rpt.Dashboard();
            Model.PoScale = 0; Model.SoScale = 0; Model.ReceivableScale = 0; Model.PayScale = 0;
        }
        var rv2 = await WtmBlazor.Api.CallAPI<List<nERP.Model.Po.Buy>>($"/api/Rpt/Dashboard/GetDashboardInTop");
        buyTop = rv2.Data;

        var rv3 = await WtmBlazor.Api.CallAPI<List<nERP.Model.So.Sale>>($"/api/Rpt/Dashboard/GetDashboardOutTop");
        saleTop = rv3.Data;
        // if (buyTop.Any())
        // {

        // }

    }
    private double GetD(decimal? V)
    {
        var v = V ?? 0;
        try
        {
            var d = Math.Round(v, 1);
            return (double)d;
        }
        catch { return 0; }
    }
    /// <summary>
    /// 日期切换
    /// </summary>
    /// <returns></returns>
    private async Task OnDateTimePickerValueChanged(DateTime dt)
    {
        Data = await GetDashboardDataAsync();
        await BarChart.Reload();
        await PieChart.Reload();
        StateHasChanged();
    }

    /// <summary>
    /// 初始化柱形图
    /// </summary>
    /// <returns></returns>
    private Task<ChartDataSource> OnInitBarChartAsync()
    {
        var ds = new ChartDataSource();
        if (Data.TestDayGroupList.Any())
        {
            var set = new ChartDataset
                {
                    Label = "",
                    Data = Data.TestDayGroupList.Select(x => x.Count).Cast<object>()
                };
            ds.Options.Title = $"{DateTimePickerValue.Year} 年 {DateTimePickerValue.Month} ";
            ds.Options.X.Title = $"{DateTimePickerValue.Month}";
            ds.Options.Y.Title = "";
            ds.Options.ShowLegend = false;
            ds.Labels = Data.TestDayGroupList.Select(x => x.Key.ToString());
            ds.Data.Add(set);
        }

        return Task.FromResult(ds);
    }

    private async Task<ChartDataSource> OnInitPieChartAsync()
    {
        var ds = new ChartDataSource();

        var rv2 = await WtmBlazor.Api.CallAPI<List<nERP.Model.Wms.BuyInWarehouseDetail>>($"/api/Rpt/Dashboard/GetDashboardPie");
        buyPie = rv2.Data;

        if (buyPie != null && buyPie.Any())
        {
            var set = new ChartDataset
                {
                    Label = $"数量",
                    Data = buyPie.Select(x => x.BuyInNumber).Cast<object>()
                };
            ds.Labels = buyPie.Select(x => $"{x.GoodsId.Substring(1)}");
            ds.Options.LegendPosition = ChartLegendPosition.Right;
            //ds.Options.ShowLegend = false;
            ds.Options.ShowXScales = false;
            ds.Options.ShowYScales = false;
            ds.Data.Add(set);
        }
        return await Task.FromResult(ds);
    }

    /// <summary>
    /// 根据数值大小获取颜色
    /// </summary>
    /// <param name = "value"></param>
    private static Color GetColor(double value) => value switch
    {
        100 => Color.Success,
        >= 50 => Color.Info,
        >= 25 => Color.Danger,
        _ => Color.Warning
    };

    private static readonly Random _random = new();

    public Task<DashboardData> GetDashboardDataAsync()
    {
        //填充随机数据，仅做展示用
        var data = new DashboardData
            {
                TestDayCount = _random.Next(10, 99),
                TestMonthCount = _random.Next(100, 999),
                TestYearCount = _random.Next(1000, 4999),
                TestAllCount = _random.Next(5000, 9999),

                TestApprovedDayCount = _random.Next(10, 59),
                TestApprovedMonthCount = _random.Next(100, 499),
                TestApprovedYearCount = _random.Next(1000, 2999),
                TestApprovedAllCount = _random.Next(4000, 4999),

                TestDayGroupList = GetDayOfMonthGroup(),
                TestKKSGroupList = GetTestKKSGroup()
            };

        //日签发占比
        var dayScale = Math.Round(data.TestApprovedDayCount / (double)data.TestDayCount * 100, 1);
        data.TestApprovedDayScale = dayScale is double.NaN ? 0 : dayScale;

        //月签发占比
        var monthScale = Math.Round(data.TestApprovedMonthCount / (double)data.TestMonthCount * 100, 1);
        data.TestApprovedMonthScale = monthScale is double.NaN ? 0 : monthScale;

        //年签发占比
        var yearScale = Math.Round(data.TestApprovedYearCount / (double)data.TestYearCount * 100, 1);
        data.TestApprovedYearScale = yearScale is double.NaN ? 0 : yearScale;

        //全部签发占比
        var allScale = Math.Round(data.TestApprovedAllCount / (double)data.TestAllCount * 100, 1);
        data.TestApprovedAllScale = allScale is double.NaN ? 0 : allScale;

        return Task.FromResult(data);
    }

    /// <summary>
    /// 按年月日分组统计
    /// </summary>
    /// <returns></returns>
    private List<TestDayGroupData> GetDayOfMonthGroup()
    {
        var result = new List<TestDayGroupData>();

        //按照当前月的每一天填充数据
        for (var i = 1; i <= 30; i++)
        {
            result.Add(new TestDayGroupData() { Key = i, Count = _random.Next(1, 99) });
        }

        return [.. result.OrderBy(x => x.Key)];
    }

    /// <summary>
    /// KKS分类分组统计
    /// </summary>
    private List<TestKKSGroupData> GetTestKKSGroup()
    {
        var result = new List<TestKKSGroupData>();

        for (var i = 0; i < 20; i++)
        {
            result.Add(new TestKKSGroupData()
                {
                    NAM = $"Blazor",
                    KKS = $"Bootstrap",
                    Count = _random.Next(10, 99),
                    Percent = _random.Next(1, 99)
                });
        }

        foreach (var item in result)
        {
            item.ApprovedCount = item.Count * (int)item.Percent / 100;
        }

        return [.. result.OrderByDescending(x => x.Percent)];
    }
    // private async Task<List<nERP.Model.Po.Buy>> GetDashboardInTop()
    // {
    //     var rv2 = await WtmBlazor.Api.CallAPI<List<nERP.Model.Po.Buy>>($"/api/Rpt/Dashboard/GetDashboardInTop");
    //     buyTop = rv2.Data;

    //     return buyTop;
    // }
}
